﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.StaticFiles;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace VideoView
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            var fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "my_video.db");
            var connStr = $"Filename={fileName}";
            services.AddDbContext<DB.MyContext>(opt =>
            {
                opt.UseSqlite(connStr, b =>
                {
                    b.MigrationsAssembly("VideoView");
                });
                //opt.UseLoggerFactory();
                opt.UseLazyLoadingProxies();
            });


            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }


            if (Configuration["auto-update-base"] == "true")
            {
                Console.WriteLine("执行数据库升级 --开始--");
                using (var serviceScope = app.ApplicationServices.GetRequiredService<IServiceScopeFactory>().CreateScope())
                {
                    serviceScope.ServiceProvider.GetService<DB.MyContext>()
                         .Database.Migrate();
                }
                Console.WriteLine("执行数据库升级 --结束--");
            }


            var fileOpt = new StaticFileOptions();
            fileOpt.ServeUnknownFileTypes = true;
// fileOpt.ContentTypeProvider = new DefaultFilesExtensions(); FileExtensionContentTypeProvider(new Dictionary<string, string> { { ".m3u8", "application/x-msdownload" } });
            app.UseStaticFiles(fileOpt);

            app.UseCookiePolicy();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            Core.ServiceLocator.Instance = app.ApplicationServices;

            Core.Status.SetVideoRoot(Configuration["videoRoot"]);
        }
    }
}
